package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    public PageInfo<StrategyDetail> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public void saveOrUpdate(StrategyDetail strategyDetail) {
        //如果没有序号
        if (strategyDetail.getSequence()==null){
            //就查询最大的序号+1进行设置
            int maxSequence = strategyDetailMapper.getMaxSequence(strategyDetail.getCatalog().getId());
            strategyDetail.setSequence(maxSequence+1);
        }
        // 判断是否是发布状态,是就设置发布时间
        if(strategyDetail.getState()==StrategyDetail.STATE_RELEASE){
            strategyDetail.setReleaseTime(new Date());
        }


        // 获取更新内容
        StrategyContent content = strategyDetail.getContent();
        if (strategyDetail.getId()!= null) { // 更新的时候不需要更新创建时间
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            // 更新攻略内容
            content.setId(strategyDetail.getId());
            contentMapper.updateByPrimaryKey(content);
        } else {
            // 设置创建时间
            strategyDetail.setCreateTime(new Date());
            strategyDetailMapper.insert(strategyDetail);
            // 没有id插入文章内容
            content.setId(strategyDetail.getId());
            contentMapper.insert(content);
        }
    }

    public StrategyDetail getByDetailsId(Long id) {

        return strategyDetailMapper.selectByPrimaryKey(id);
    }

    public StrategyContent getContentById(Long id) {

        return contentMapper.selectByPrimaryKey(id);
    }

}
